// src/hooks/useOnlineCollecting.ts
import { useState } from 'react';
import { useRequest } from 'umi';
import {
  queryArchiveTypes,
  queryTableData,
  deleteRecords,
  batchUpdateRecords,
} from '@/services/prefiling/onlineCollecting';
import { ArchiveType, ArchiveRecord, ArchiveTabType } from '@/types/prefiling/onlineCollecting';

export default function useOnlineCollecting() {
  const [currentType, setCurrentType] = useState<ArchiveType | null>(null);
  const [activeTab, setActiveTab] = useState<ArchiveTabType>('roll');
  const [selectedRows, setSelectedRows] = useState<React.Key[]>([]);
  const [queryConditions, setQueryConditions] = useState<Record<string, any>>({});

  // 档案类型树数据
  const { data: archiveTypes, run: fetchArchiveTypes } = useRequest(queryArchiveTypes, {
    manual: true,
  });

  // 表格数据
  const {
    data: tableData,
    loading: tableLoading,
    run: fetchTableData,
  } = useRequest(
    (params: { type: ArchiveTabType; query?: Record<string, any> }) => {
      if (!currentType) return Promise.resolve({ data: [] });
      return queryTableData({
        typeCode: currentType.typeCode,
        arrangeDimension: currentType.arrangeDimension,
        fullId: currentType.fullId,
        ...params.query,
      });
    },
    {
      manual: true,
      formatResult: (res) => res.data,
    }
  );

  // 删除记录
  const { run: batchDelete } = useRequest(deleteRecords, {
    manual: true,
    onSuccess: () => {
      fetchTableData({ type: activeTab, query: queryConditions });
      setSelectedRows([]);
    },
  });

  // 批量更新
  const { run: batchUpdate } = useRequest(batchUpdateRecords, {
    manual: true,
    onSuccess: () => {
      fetchTableData({ type: activeTab, query: queryConditions });
      setSelectedRows([]);
    },
  });

  return {
    state: {
      archiveTypes: archiveTypes?.data || [],
      currentType,
      tableData: tableData || [],
      tableLoading,
      activeTab,
      selectedRows,
      queryConditions,
    },
    actions: {
      fetchArchiveTypes,
      setCurrentType,
      fetchTableData,
      batchDelete,
      batchUpdate,
      setActiveTab,
      setSelectedRows,
      setQueryConditions,
    },
  };
}